/******************************************************************************
Module:  CountdownTimer.cs
Notices: Copyright (c) 2006-2007 by Jeffrey Richter and Wintellect
******************************************************************************/


using System;
using System.Threading;
using System.Diagnostics;


///////////////////////////////////////////////////////////////////////////////


namespace Microsoft.OfficeCommunicationsServer.Applications.Threading.Threading.AsyncProgModel {
   [DebuggerStepThrough]
   public sealed class CountdownTimer : IDisposable {
      private AsyncResult m_asyncResult;
      private Timer m_timer;

      public CountdownTimer() {}
      public IAsyncResult BeginCountdown(Int32 ms, AsyncCallback ac, Object state) {
         Interlocked.Exchange(ref m_asyncResult, new AsyncResult(ac, state));
         m_timer = new Timer(CountdownDone, null, ms, Timeout.Infinite);
         return m_asyncResult;
      }

      private void CountdownDone(Object state) {
         m_asyncResult.SetAsCompleted(null, false);
         m_timer.Dispose();
         m_timer = null;
      }

      public void EndCountdown(IAsyncResult result) {
         ((AsyncResult) result).EndInvoke();
      }

      public void Dispose() {
         if (m_timer == null) return;
         m_timer.Dispose(); 
         m_timer = null;
      }
   }
}


//////////////////////////////// End of File //////////////////////////////////